from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from home import models, homeser
from rest_framework.generics import ListAPIView, CreateAPIView
from django.core.files.storage import default_storage
from django.core.cache import cache


class HeadNavi(APIView):
    def get(self, request):
        key = "headnav"
        navlist = cache.get(key)
        if navlist:
            return Response({"code": 200, "msg": "ok", "data": navlist})
        navlist = models.Nav.objects.filter(position=0, flag=True).order_by("order")
        ser = homeser.NacSer(navlist, many=True)
        cache.set(key, ser.data, 60 * 60 * 24)
        return Response({"code": 200, "msg": "ok", "data": ser.data})


class FootNavi(APIView):
    def get(self, request):
        nav = models.Nav.objects.filter(position=1, flag=True).order_by('order')
        ser = homeser.NacSer(nav, many=True)
        return Response({"code": 200, "msg": "ok", "data": ser.data})


# class Banner(APIView):
#     def get(self, request):
#         banner = models.Banner.objects.filter(flag=True).order_by('order')
#         ser = homeser.BannerSer(banner, many=True)
#         data = ser.data
#         for item in data:
#             item['imgurl'] = "http://127.0.0.1:8000/uploads" + item['imgurl']
#         return Response({"code": 200, "msg": "ok", "data": data})


class BannerList(ListAPIView):
    queryset = models.Banner.objects.filter(flag=True).order_by('order')
    serializer_class = homeser.BannerSer


class UploadFile(APIView):
    def post(self, request):
        file = request.data.get("file")
        types = ['jpg', 'png', 'jpeg']
        if file.name.split(".")[-1] not in types:
            return Response({"code": 201, "msg": "上传的文件类型不对"})
        if file.size > 2 * 1024 * 1024:
            return Response({"code": 201, "msg": "上传的文件过大"})
        uploadfile = default_storage.save(file.name, file)
        url = default_storage.url(uploadfile)
        return Response({"url": url})


class Add(CreateAPIView):
    queryset = models.Banner.objects.all()
    serializer_class = homeser.BannerSer
